package com.kly.smartbi.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

import static com.kly.smartbi.constant.CommonConstant.LOCK_PREFIX;

/**
 * @author admin
 * @date 2025/4/9
 */
public class SimpleRedissonLock {

    private final RedissonClient redissonClient;

    public SimpleRedissonLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 尝试加锁
     * @param keyPrefix
     * @param expireTime
     * @return
     */
    public boolean tryLock(String keyPrefix, Integer expireTime) throws InterruptedException {
        String key = LOCK_PREFIX + keyPrefix;
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock(10, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 尝试加锁
     * @param keyPrefix
     * @return
     * @throws InterruptedException
     */
    public boolean tryLock(String keyPrefix) throws InterruptedException {
        String key = LOCK_PREFIX + keyPrefix;
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock(10, TimeUnit.MINUTES);
    }

    /**
     * 释放锁
     * @param keyPrefix
     */
    public void unLock(String keyPrefix) {
        String key = LOCK_PREFIX + keyPrefix;
        RLock lock = redissonClient.getLock(key);
        lock.unlock();
    }
}
